package com.demo.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.demo.beans.Bean;
import com.demo.beans.Filename;
import com.demo.beans.ReturnData;
import com.demo.service.Impl.BeanServiceImpl;
import com.demo.service.Impl.FileService;
import com.demo.service.Impl.FilenameService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("file")
public class FileController {
    public static void main(String[] args) {
//        Date date = new Date();
//        SimpleDateFormat timeFormat= new SimpleDateFormat("yyyymmddHHmmss");
//        SimpleDateFormat dayFormat= new SimpleDateFormat("yyyyMMdd");
//        SimpleDateFormat monthFormat= new SimpleDateFormat("yyyyMM");
//        Calendar cal = Calendar.getInstance();
//        cal.setTime(date);
//        cal.add(Calendar.DATE,-1);
//        //昨天晚上23点59分59秒
//        String startTime = dayFormat.format(cal.getTime()) + "235959";
//        //当前时间
//        String endTime = timeFormat.format(date);
//        cal.setTime(date);
//        cal.add(Calendar.MONTH,-1);
//        //上个月月份
//        String beforeMonth = monthFormat.format(cal.getTime());
//        String theMonth = monthFormat.format(date);
//        System.out.println(startTime);
//        System.out.println(endTime);
//        System.out.println(beforeMonth);
//        System.out.println(theMonth);
        long l1 = System.currentTimeMillis();
        Date date = new Date(l1);
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = dateformat.format(date);
        System.out.println(format);
        System.out.println(l1);
    }

    public static String getYesterday(String today){
        today = today.substring(0,8);
        return today;
    }
    @Autowired
    private FileService fileService;
    @Autowired
    private BeanServiceImpl beanService;
    @Autowired
    private FilenameService filenameService;

    @RequestMapping("upload")
    public ReturnData uploadFile(@RequestParam("file")MultipartFile file){
        ReturnData returnData = BaseAction.createReturnData();
        String originalFilename = file.getOriginalFilename();
        Filename filename = filenameService.findByName(originalFilename);
        if (ObjectUtil.isNotEmpty(filename)){
            returnData.put("returnCode","9999");
            returnData.put("returnMsg","您已上传过该文件，请确认是否上传过该文件的内容，若确定未上传，请更换文件名称重新上传");
            return returnData;
        }
        try {
            List<Bean> beanList = this.fileService.analysisFile(file);
            boolean b = beanService.batchSave(beanList);
            String fileNameId = filenameService.saveFilename(originalFilename);
            if (b && fileNameId.length() >= 0){
                returnData.put("fileNameId",fileNameId);
                returnData.put("returnCode","0000");
                returnData.put("returnMsg","解析完成。");
            }
        } catch (IOException e) {
            e.printStackTrace();
            returnData.put("returnMsg","解析失败" + e);
            return returnData;
        }
        return returnData;
    }

    @GetMapping("outputExcel")
    public void outputExcel(@RequestParam("allDom") String allDom, @RequestParam("queryCondition") String queryCondition, HttpServletResponse response) {
        ReturnData returnData = BaseAction.createReturnData();
        HSSFWorkbook workbook = fileService.outputExcel(allDom, queryCondition);
        OutputStream os = null;
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ServletOutputStream outputStream = response.getOutputStream();
            this.setResponseHeader(response,queryCondition);
            //将写好的workbook写到流中
            workbook.write(byteArrayOutputStream);
            //拷贝输出流内容到一个新的字节数组
            outputStream.write(byteArrayOutputStream.toByteArray());
            outputStream.flush();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            response.setHeader("Pragma", "public");
            response.setHeader("Cache-Control", "no-store");
            response.addHeader("Cache-Control", "max-age=0");
            response.addDateHeader("Expires", 0);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @GetMapping("outputExcel1")
    public void outputExcel1(@RequestParam("queryCondition") String queryCondition, HttpServletResponse response) {
        ReturnData returnData = BaseAction.createReturnData();
       /* Map<String, String> parse = (Map<String, String>) JSON.parse(queryCondition);
        String beginYear = parse.get("beginYear");
        String endYear = parse.get("endYear");
        String schoolName = parse.get("schoolName");
        String branch = parse.get("branch");
        String major = parse.get("major");
        String zdfwc = parse.get("zdfwc");*/
       String fileName = "";
        String[] split = queryCondition.split("-");
        String beginYear = split[0];
        if ("aa".equals(beginYear)) {
            beginYear = "";
        }
        String endYear = split[1];
        if ("aa".equals(endYear)) {
            endYear = "";
        }
        String schoolName = split[2];
        if ("aa".equals(schoolName)) {
            schoolName = "";
        }
        String branch = split[3];
        if ("aa".equals(branch)) {
            branch = "";
        }
        String major = split[4];
        if ("aa".equals(major)) {
            major = "";
        }
        String zdfwc = split[5];
        if ("aa".equals(zdfwc)) {
            zdfwc = "";
        }
        List<Bean> beanList = beanService.qbByCondition(beginYear, endYear, schoolName, branch, major, zdfwc);
        HSSFWorkbook workbook = fileService.outputExcel(beanList);
        OutputStream os = null;
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ServletOutputStream outputStream = response.getOutputStream();
            Date date = new Date();
            SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
            String format = dateFormat.format(date);
            format = format.replace(" :","").replace(":","").replace("-","");
            queryCondition = queryCondition.replace("aa-","").replace("-aa","");
            if ("aa".equals(queryCondition)){
                queryCondition = "";
            }
            queryCondition = format + "_" + queryCondition + ".xlsx";
            this.setResponseHeader(response,queryCondition);
            //将写好的workbook写到流中
            workbook.write(byteArrayOutputStream);
            //拷贝输出流内容到一个新的字节数组
            outputStream.write(byteArrayOutputStream.toByteArray());
            outputStream.flush();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
